import logging
from datetime import datetime, timedelta
import json

from django.http import JsonResponse

from django.shortcuts import HttpResponse
from django.db.models import Q
from web.models import User
import hashlib
from web.views.utils import is_valid_username, get_curtime

user_logger = logging.getLogger('user_management')


def login(request):
    """用户登录"""
    # 接收前端传递过来的值
    data = json.loads(request.body.decode("utf-8"))
    try:
        username = data['Username']  # 获取其中一个字段信息
        password = data['Password']  # 获取其中一个字段信息

        # 查找到要登录的用户信息
        obj_user_set = User.objects.filter(user_name=username, is_delete=0)
        if not obj_user_set:
            user_logger.error(f"用户<{username}>登录失败，该用户不存在")
            return JsonResponse({'code': '1', 'msg': "该用户不存在！"})
        obj_user = obj_user_set[0]
        # 密码校验
        if password == obj_user.password:
            # 生成token
            token = hashlib.md5(
                (username + password + datetime.now().strftime('%Y-%m-%d %H:%M:%S')).encode('utf-8')).hexdigest()
            data = {'user_id': obj_user.user_id, 'user_name': obj_user.user_name, 'user_level': obj_user.user_level}
            user_logger.info(f"用户<{username}>登录成功")
            response = JsonResponse({'code': '0', 'msg': f"用户<{username}>登录成功！", 'data': data})
            # 创建一个名为 'token' 的 cookie，并设置其值为token
            response.set_cookie('token', token, expires=datetime.now() + timedelta(days=3))
            return response

    except Exception as e:
        user_logger.error(f"登录过程出现异常，具体原因：{str(e)}")
        return JsonResponse({'code': '1', 'msg': "登录过程出现异常，具体原因：" + str(e)})


def register(request):
    """注册新用户"""
    # 接收前端传递过来的值
    data = json.loads(request.body.decode("utf-8"))
    try:
        username = data['Username']  # 获取其中一个字段信息
        password = data['Password']  # 获取其中一个字段信息

        # 检查用户名是否已经被使用
        if User.objects.filter(user_name=username, is_delete=0).exists():
            user_logger.error(f"注册过程失败，具体原因：<{username}>用户名已被使用")
            return JsonResponse({'code': '1', 'msg': "用户名已经被使用，请选择其他用户名！"})

        flag, msg = is_valid_username(username)  # 用户名合法性检验
        # 不合法
        if not flag:
            user_logger.error(f"注册过程失败，具体原因：<{username}>用户名不合法：{msg}")
            return JsonResponse({'code': '1', 'msg': msg})
        # 合法，存储数据库
        else:
            # 添加到数据库
            obj_user = User(user_name=username, password=password,
                            create_time=get_curtime(), is_delete=0,
                            user_level=0)
            # 执行添加
            obj_user.save()
            user_logger.info(f"新用户<{username}>注册成功！")
            return JsonResponse({'code': '0', 'msg': f"新用户<{username}>注册成功！"})
    except Exception as e:
        return JsonResponse({'code': '1', 'msg': "添加到数据库出现异常，具体原因：" + str(e)})


def logout(request):
    """退出登录"""
    try:
        response = JsonResponse({'code': '0', 'msg': f"用户退出登录！"})
        response.delete_cookie('token')  # 删除名为 'token' 的 cookie
        return response
    except Exception as e:
        user_logger.error(f"注册过程出现异常，具体原因：{str(e)}")
        return JsonResponse({'code': '1', 'msg': "过程出现异常，具体原因：" + str(e)})


def logoff(request):
    """用户注销"""
    # 接收前端传递过来的值
    data = json.loads(request.body.decode("utf-8"))
    try:
        username = data['Username']  # 获取其中一个字段信息
        password = data['Password']  # 获取其中一个字段信息
        # 查找到要注销的用户信息
        obj_user_set = User.objects.filter(user_name=username, is_delete=0)
        obj_user = obj_user_set[0]
        # 密码校验
        if password == obj_user.password:
            obj_user.is_delete = 1
            obj_user.delete_time = get_curtime()
            obj_user.save()
            user_logger.info(f"用户<{username}>已注销！")
            response = JsonResponse({'code': '0', 'msg': f"用户<{username}>已注销！"})
            response.delete_cookie('token')  # 删除名为 'token' 的 cookie
        else:
            response = JsonResponse({'code': '1', 'msg': f"用户名或密码错误！"})
        return response
    except Exception as e:
        user_logger.error(f"用户注销过程出现异常，具体原因：{str(e)}")
        return JsonResponse({'code': '1', 'msg': "过程出现异常，具体原因：" + str(e)})


def permission_judge(request):
    return HttpResponse("登录页面")


def CheckLogin(request):
    """
    判断用户是否登录
    """
    try:
        token = request.COOKIES.get('token')
        # 校验
        if token:
            return JsonResponse({'code': '0', 'msg': f"用户已登录！"})
        else:
            return JsonResponse({'code': '10010', 'msg': f"用户未登录！"})
    except Exception as e:
        user_logger.error(f"用户登录验证过程出现异常，具体原因：{str(e)}")
        return JsonResponse({'code': '1', 'msg': "过程出现异常，具体原因：" + str(e)})


def get_users(request):
    """获取用户列表"""
    # 接收前端传递过来的值
    data = json.loads(request.body.decode("utf-8"))
    # 请求该接口的用户id
    userId = request.META.get('HTTP_USERID')
    try:
        # 获取该接口id对应的用户权限
        result_userId = User.objects.filter(user_id=userId).values("user_level")
        if result_userId[0]["user_level"] == 2:
            page_num = data['page_num']  # 当前界面
            page_size = data['page_size']  # 页面大小
            q_filters = Q()
            # 判断关键字是否为空
            if data['user_id'] != '':
                q_filters |= Q(user_id__icontains=data['user_id'])
            if data['user_name'] != '':
                q_filters |= Q(user_name__icontains=data['user_name'])
            if data['user_level'] != '':
                q_filters |= Q(user_level__icontains=data['user_level'])
            q_filters &= Q(is_delete=0)
            q_filters &= (Q(user_level=0) | Q(user_level=1))
            result = User.objects.filter(q_filters).values("user_id", "user_name", "user_level")
            result_total_user = User.objects.filter((Q(user_level=0) | Q(user_level=1)) & Q(is_delete=0))
            total_users = result_total_user.count()
            result_approve_users = User.objects.filter(Q(user_level=1) & Q(is_delete=0))
            approve_users = result_approve_users.count()
            output = []
            for data_result in result:
                data_dict = {
                    'user_id': str(data_result["user_id"]),
                    'username': data_result["user_name"],
                    'user_level': data_result["user_level"]
                }
                output.append(data_dict)
            # 计算总数
            search_num = result.count()

            # 计算分页索引
            index_start = page_size * (page_num - 1)
            index_end = index_start + page_size
            if index_start > search_num:
                user_logger.error("需要查询的订单信息页面大于订单数量__查询失败")
                return JsonResponse({'code': '1', 'msg': "查询失败，原因是分页参数错误"})
            else:
                data_list = output[index_start: index_end]
                data = {'total_users': total_users, 'approve_users': approve_users, 'search_num': search_num,
                        'user_list': data_list}

            return JsonResponse({'code': '0', 'msg': "获取用户列表信息成功！", 'data': data})
        else:
            return JsonResponse({'code': '1', 'msg': "用户权限不足！", 'data': "null"})

    except Exception as e:
        # return JsonResponse({'code': '1', 'msg': "获取用户列表信息过程出错，具体原因：" + str(e)})
        user_logger.error(f"获取用户列表信息过程出现异常，具体原因：{str(e)}")
        return JsonResponse({'code': '1', 'msg': "获取用户列表信息失败！", 'data': "null"})


def set_user_level(request):
    """设置用户权限级别"""
    # 接收前端传递过来的值
    data = json.loads(request.body.decode("utf-8"))
    # 请求该接口的用户id
    userId = request.META.get('HTTP_USERID')
    try:
        # 获取该接口id对应的用户权限
        result_userId = User.objects.filter(user_id=userId).values("user_level")
        if result_userId[0]["user_level"] == 2:
            update_data = User.objects.get(user_id=data['user_id'])
            update_data.user_level = data["user_level"]
            update_data.save()
            change_user_level = "普通用户" if data["user_level"] == 0 else "管理员"
            user_logger.info(f"用户<{update_data.user_name}>权限更改为{change_user_level}")
            return JsonResponse({'code': '0', 'msg': "用户权限更改成功！", 'data': "null"})
        else:
            return JsonResponse({'code': '1', 'msg': "用户权限不足！", 'data': "null"})

    except Exception as e:
        # return JsonResponse({'code': '1', 'msg': "用户权限更改过程出错，具体原因：" + str(e)})
        user_logger.error(f"用户权限更改过程出错，具体原因：{str(e)}")
        return JsonResponse({'code': '1', 'msg': "用户权限更改失败！", 'data': "null"})


def user_delete(request):
    """删除用户信息"""
    # 接收前端传递过来的值
    data = json.loads(request.body.decode("utf-8"))
    # 请求该接口的用户id
    userId = request.META.get('HTTP_USERID')
    try:
        # 获取该接口id对应的用户权限
        result_userId = User.objects.filter(user_id=userId).values("user_level")
        if result_userId[0]["user_level"] == 2:
            user_id = data['user_id']  # 获取其中一个字段信息
            # 查找到要注销的用户信息
            obj_user = User.objects.get(user_id=user_id, is_delete=0)

            obj_user.is_delete = 1
            obj_user.delete_time = get_curtime()
            obj_user.save()
            user_logger.info(f"用户<{obj_user.user_name}>删除成功")
            response = JsonResponse({'code': '0', 'msg': f"用户删除成功！"})
        else:
            response = JsonResponse({'code': '1', 'msg': "用户权限不足！", 'data': "null"})
        return response
    except Exception as e:
        user_logger.error(f"用户删除过程出现异常，具体原因：{str(e)}")
        return JsonResponse({'code': '1', 'msg': "过程出现异常，具体原因：" + str(e)})
